package org.ruoyi.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.RequiredArgsConstructor;
import org.ruoyi.service.IHC28Service;
import org.ruoyi.system.service.ISysConfigService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;

/**
 * @className: HC28ServiceImpl
 * @Description: HC28实现
 * @author: lethe
 * @date: 2025/10/24 16:39
 */
@RequiredArgsConstructor
@Service
public class HC28ServiceImpl implements IHC28Service {

    private Logger logger = LoggerFactory.getLogger(HC28ServiceImpl.class);

    @Autowired
    private ISysConfigService configService;

    private String uploadImage(String COMFYUI_SERVER, String url) {
        try {
            // 从URL下载图片到临时文件
            File tempFile = FileUtil.createTempFile();
            long size = HttpUtil.downloadFile(url, tempFile);
            System.out.println("Download size: " + size);

            URI uri = new URI(COMFYUI_SERVER).resolve("/upload/image");

            // 使用Hutool的HttpUtil正确上传文件到ComfyUI
            // ComfyUI的/upload/image端点需要multipart/form-data格式，文件参数名为"image"
            String result = HttpUtil.createPost(uri.toString())
                    .form("image", tempFile)  // 文件参数名应为"image"
                    .form("type", "input")     // 其他参数使用form方法添加
                    .form("overwrite", "true")
                    .execute()
                    .body();
            
            // 删除临时文件
            FileUtil.del(tempFile);
            
            // 解析响应JSON，提取name字段
            JSONObject responseJson = new JSONObject(result);
            return responseJson.getStr("name");
        } catch (Exception e) {
            throw new RuntimeException("上传图片失败: " + e.getMessage(), e);
        }
    }

    @Override
    public String submit(JSONObject params) {
        String COMFYUI_SERVER = configService.selectConfigByKey("comfyui-server");

        if(StrUtil.isEmptyOrUndefined(COMFYUI_SERVER)){
            throw new RuntimeException("未配置ComfyUI服务器地址");
        }

        try {
            String baseImageUrl = params.getStr("baseImage");
            if(StrUtil.isEmptyOrUndefined(baseImageUrl)){
                throw new RuntimeException("未检测到家装图片");
            }

            String furnitureImageUrl = params.getStr("furnitureImage");
            if(StrUtil.isEmptyOrUndefined(furnitureImageUrl)){
                throw new RuntimeException("未检测到家具图片");
            }

            // 上传图片到ComfyUI服务器
            String baseImageName = uploadImage(COMFYUI_SERVER, baseImageUrl);
            String furnitureImageName = uploadImage(COMFYUI_SERVER, furnitureImageUrl);

            JSONObject promptObj = params.getJSONObject("prompt");

            JSONObject node35 = promptObj.getJSONObject("35");
            if(node35 != null) {
                JSONObject inputs = node35.getJSONObject("inputs");
                if(inputs == null) {
                    inputs = new JSONObject();
                }
                inputs.set("image", baseImageName);
            }
            promptObj.set("35", node35);

            JSONObject node83 = promptObj.getJSONObject("83");
            if(node83 != null) {
                JSONObject inputs = node83.getJSONObject("inputs");
                if(inputs == null) {
                    inputs = new JSONObject();
                }
                inputs.set("image", furnitureImageName);
            }
            promptObj.set("83", node83);


            JSONObject prompt = new JSONObject();
            prompt.set("prompt", promptObj);

            URI uri = new URI(COMFYUI_SERVER).resolve("/prompt");
            logger.info(prompt.toStringPretty());

            return HttpRequest.post(uri.toString())
                    .header("Content-Type", "application/json")
                    .body(prompt.toString())
                    .execute()
                    .body();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public String getComfyUIServer(String endpoint) {
        String COMFYUI_SERVER = configService.selectConfigByKey("comfyui-server");
        URI uri = null;
        try {
            uri = new URI(COMFYUI_SERVER);
        } catch (URISyntaxException e) {
            logger.error(e.getMessage());
            return "";
        }
        if(StrUtil.isNotBlank(endpoint)){
            uri = uri.resolve(endpoint);
        }
        return uri.toString();
    }

    @Override
    public String getComfyUIServerWs() {
        String COMFYUI_SERVER = configService.selectConfigByKey("comfyui-server");
        if (StrUtil.isEmptyOrUndefined(COMFYUI_SERVER)) {
            return "";
        }
        
        try {
            if(!COMFYUI_SERVER.endsWith("/")){
                COMFYUI_SERVER += "/";
            }
            // 将HTTP协议替换为WebSocket协议
            if (COMFYUI_SERVER.startsWith("https://")) {
                return COMFYUI_SERVER.replaceFirst("https://", "wss://") + "ws";
            } else if (COMFYUI_SERVER.startsWith("http://")) {
                return COMFYUI_SERVER.replaceFirst("http://", "ws://") + "ws";
            } else {
                // 如果没有协议前缀，默认使用ws协议
                return "ws://" + COMFYUI_SERVER + "ws";
            }
        } catch (Exception e) {
            logger.error("生成ComfyUI WebSocket地址失败: " + e.getMessage(), e);
            return "";
        }
    }
}
